# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk, scrolledtext, colorchooser, filedialog
from PIL import Image, ImageDraw, ImageFont, ImageTk
import math
import os

# 微信视频号标准尺寸
WIDTH_WECHAT, HEIGHT_WECHAT = 1080, 1260
WIDTH_VERTICAL, HEIGHT_VERTICAL = 1080, 1920
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")

# 新增：载入背景图片功能
def load_background_image():
    """载入背景图片"""
    try:
        file_path = filedialog.askopenfilename(
            title="选择背景图片",
            filetypes=[("图片文件", "*.png *.jpg *.jpeg")]
        )
        if file_path:
            global background_image_path
            background_image_path = file_path
            log_text.configure(state='normal')
            log_text.delete(1.0, tk.END)
            log_text.insert(tk.END, f"背景图片已载入：{file_path}")
            log_text.configure(state='disabled')

            # 新增：显示背景图片预览
            preview_window = tk.Toplevel(root)
            preview_window.title("背景图片预览")
            preview_window.geometry("300x300")
            img = Image.open(file_path).resize((300, 300))
            img_tk = ImageTk.PhotoImage(img)
            preview_label = ttk.Label(preview_window, image=img_tk)
            preview_label.image = img_tk  # 防止图片被垃圾回收
            preview_label.pack(fill=tk.BOTH, expand=True)

    except Exception as e:
        log_text.configure(state='normal')
        log_text.delete(1.0, tk.END)
        log_text.insert(tk.END, f"错误：{str(e)}")
        log_text.configure(state='disabled')

# 修改：generate_cover 函数，支持使用载入的背景图片
def generate_cover(cover_type):
    """生成封面主逻辑"""
    try:
        intro_title = entry_intro.get().strip()  # 新增：获取引言标题
        main_title = entry_main.get().strip()
        sub_title = entry_sub.get().strip()

        # 根据封面类型选择尺寸
        if cover_type == "wechat":
            WIDTH, HEIGHT = WIDTH_WECHAT, HEIGHT_WECHAT
        elif cover_type == "vertical":
            WIDTH, HEIGHT = WIDTH_VERTICAL, HEIGHT_VERTICAL

        # # 校验引言标题长度
        # if len(intro_title) > 9:
        #     raise ValueError("引言标题不得超过9字")
        #
        # # 校验主标题和副标题长度
        # if not main_title or len(main_title) > 5:
        #     raise ValueError("主标题不能为空且不得超过5字")
        # if not sub_title or len(sub_title) > 8:
        #     raise ValueError("副标题不能为空且不得超过8字")

        # 使用载入的背景图片或默认背景图片
        if 'background_image_path' in globals():
            base_img = Image.open(background_image_path).resize((WIDTH, HEIGHT))
        else:
            if not os.path.exists("1.png"):
                # 创建渐变深蓝色背景
                base_img = Image.new('RGB', (WIDTH, HEIGHT))
                draw = ImageDraw.Draw(base_img)
                for i in range(HEIGHT):
                    color = (0, 0, int(255 * (i / HEIGHT)))
                    draw.line((0, i, WIDTH, i), fill=color)
            else:
                base_img = Image.open("1.png").resize((WIDTH, HEIGHT))

        # 主标题字体设置
        main_font_size = int(HEIGHT * 0.08)  # 调整主标题字体大小
        main_font = ImageFont.truetype("simhei.ttf", main_font_size)

        # 副标题字体设置
        sub_font_size = int(HEIGHT * 0.05)  # 调整副标题字体大小
        sub_font = ImageFont.truetype("simhei.ttf", sub_font_size)

        # 引言标题字体设置
        intro_font_size = int(HEIGHT * 0.05)  # 引言标题字体大小与副标题一致
        intro_font = ImageFont.truetype("simhei.ttf", intro_font_size)

        # 文字居中绘制
        draw = ImageDraw.Draw(base_img)

        # 计算引言标题位置
        intro_text_bbox = draw.textbbox((0, 0), intro_title, font=intro_font)
        intro_x = (WIDTH - (intro_text_bbox[2] - intro_text_bbox[0])) // 2
        intro_y = HEIGHT // 4  # 引言标题位于主标题上方

        # 计算主标题位置
        main_text_bbox = draw.textbbox((0, 0), main_title, font=main_font)
        main_x = (WIDTH - (main_text_bbox[2] - main_text_bbox[0])) // 2
        main_y = HEIGHT // 3  # 主标题位于引言标题下方，间隔一致

        # 计算副标题位置
        sub_text_bbox = draw.textbbox((0, 0), sub_title, font=sub_font)
        sub_x = (WIDTH - (sub_text_bbox[2] - sub_text_bbox[0])) // 2
        sub_y = HEIGHT // 2.3  # 副标题位于主标题下方，间隔一致

        # 添加引言标题文字阴影效果
        shadow_color = (30, 30, 30)  # 新增：定义阴影颜色
        draw.text((intro_x + 3, intro_y + 3), intro_title, fill=shadow_color, font=intro_font)
        draw.text((intro_x, intro_y), intro_title, fill=(255, 255, 255), font=intro_font)

        # 添加文字阴影效果
        draw.text((main_x + 3, main_y + 3), main_title, fill=shadow_color, font=main_font)
        draw.text((main_x, main_y), main_title, fill=(255, 255, 255), font=main_font)

        draw.text((sub_x + 3, sub_y + 3), sub_title, fill=shadow_color, font=sub_font)
        draw.text((sub_x, sub_y), sub_title, fill=(255, 255, 255), font=sub_font)

        # 保存文件
        if cover_type == "wechat":
            filename = f"微信封面_{main_title[:5]}_{sub_title[:8]}.jpg"
        else:
            filename = f"竖版封面_{main_title[:5]}_{sub_title[:8]}.jpg"
        save_path = os.path.join(desktop_path, filename)
        base_img.save(save_path, quality=95)

        log_text.configure(state='normal')
        log_text.delete(1.0, tk.END)
        log_text.insert(tk.END, f"封面生成成功！\n保存路径：{save_path}")
        log_text.configure(state='disabled')

    except Exception as e:
        log_text.configure(state='normal')
        log_text.delete(1.0, tk.END)
        log_text.insert(tk.END, f"错误：{str(e)}")
        log_text.configure(state='disabled')

# 创建主窗口
root = tk.Tk()
root.title("视频封面生成工具 by:风二西  2025.03.29 ")
root.geometry("500x300")
# 定义 main_frame
main_frame = ttk.Frame(root)
main_frame.pack(pady=1, padx=1, fill=tk.BOTH, expand=True)

# GUI组件
input_frame = ttk.Frame(main_frame)
input_frame.pack(pady=1, fill=tk.X)

# 新增：引言标题输入框
f1 = ttk.Frame(input_frame)
f1.pack(pady=5, fill=tk.X)

ttk.Label(f1, text="引标题（9字）：", font=('微软雅黑', 10)).pack(side=tk.LEFT, padx=10, pady=5)
entry_intro = ttk.Entry(f1, width=30, font=('微软雅黑', 10))
entry_intro.pack(padx=1, pady=1, fill=tk.X, expand=True)

f2 = ttk.Frame(input_frame)
f2.pack(pady=5, fill=tk.X)
# 主标题和副标题的行号调整
ttk.Label(f2, text="主标题（5字）：", font=('微软雅黑', 10)).pack(side=tk.LEFT, padx=10, pady=5)
entry_main = ttk.Entry(f2, width=30, font=('微软雅黑', 10))
entry_main.pack(padx=1, pady=1, fill=tk.X, expand=True)

f3 = ttk.Frame(input_frame)
f3.pack(pady=5, fill=tk.X)
ttk.Label(f3, text="副标题（8字）：", font=('微软雅黑', 10)).pack(side=tk.LEFT, padx=10, pady=5)
entry_sub = ttk.Entry(f3, width=30, font=('微软雅黑', 10))
entry_sub.pack(padx=1, pady=1, fill=tk.X, expand=True)

input_frame2 = ttk.Frame(main_frame)
input_frame2.pack(pady=1, fill=tk.X)

generate_btn_wechat = ttk.Button(input_frame2, text="视频号封面", command=lambda: generate_cover("wechat"))
generate_btn_wechat.pack(side=tk.LEFT, pady=1, padx=10)

generate_btn_vertical = ttk.Button(input_frame2, text="普通竖版封面", command=lambda: generate_cover("vertical"))
generate_btn_vertical.pack(side=tk.LEFT, pady=1, padx=10)

# 新增：载入背景图片按钮
ttk.Button(input_frame2, text="载入背景图片", command=load_background_image).pack(side=tk.LEFT, pady=10, padx=10)

log_frame = ttk.Frame(main_frame)
log_frame.pack(pady=1, fill=tk.BOTH, expand=True)

log_text = scrolledtext.ScrolledText(log_frame, height=3, wrap=tk.WORD, font=('微软雅黑', 10))
log_text.pack(fill=tk.BOTH, expand=True)
log_text.configure(state='disabled')

# 新增：关注提示标签
follow_frame = ttk.Frame(main_frame)
follow_frame.pack(pady=1, fill=tk.X)
ttk.Label(follow_frame, text="更多教程和工具，欢迎关注B站风二西", font=('微软雅黑', 10), foreground='').pack(side=tk.RIGHT, padx=10, pady=5)

root.mainloop()